//定义全局方法。
const cp = {};
var flyEvent;
cp.viewer = null;
cp.geojsonData = {};
cp.currentEntity = null;
//三维球初始化
cp.cesiumInit = function () {
    cp.viewer = new GV.GeoCanvas('cesiumContainer', {
        shouldAnimate: true,
        animation: true,
        // baseLayerPicker: true,
        // imageryProvider :Cesium.createTileMapServiceImageryProvider({
        //     url: Cesium.buildModuleUrl('/dist/Assets/Textures/NaturalEarthII')
        // }),
        // imageryProvider: new Cesium.WebMapServiceImageryProvider({
        //     url: `http://icenter.geovis.online/tilecache/service/wms`,
        //     layers: 'Global_Image-JPEG-4326',
        //     parameters: {
        //         format: 'image/jpeg'
        //     },
        //     srs: 'EPSG:4326'
        // })
        // imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
        //     // url: "http://mt1.google.cn/vt/lyrs=s&hl=zh-CN&x={x}&y={y}&z={z}&s=Gali"
        //     url:'http://icenter.geovis.online/tilecache/service/wmts',
        //     layers: 'Global_Image-JPEG-4326',
        //     parameters: {
        //         format: 'image/jpeg'
        //     },
        //     srs: 'EPSG:4326'
        //     // layers:'Global_Image-JPEG-4326',
        //     // format: "image/jpeg",
        //     // style: "default",
        //     // maximumLevel:18,
        //     // tileMatrixSetID: "EPSG:4326",
        //     // tileMatrixLabels:["EPSG:4326:0","EPSG:4326:1","EPSG:4326:2","EPSG:4326:3","EPSG:4326:4","EPSG:4326:5","EPSG:4326:6","EPSG:4326:7","EPSG:4326:8","EPSG:4326:9","EPSG:4326:10","EPSG:4326:11","EPSG:4326:12","EPSG:4326:13","EPSG:4326:14","EPSG:4326:15","EPSG:4326:16","EPSG:4326:17"]
        //     //tilingScheme: new GV.GeographicTilingScheme(),
        // }),
        // geocoder:false
    });
    cp.viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
        "url": "http://mt1.google.cn/vt/lyrs=s&hl=zh-CN&x={x}&y={y}&z={z}&s=Gali",
        "maximumLevel": 21
    }));
    var url="http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg"+"&tk="+'19b72f6cde5c8b49cf21ea2bb4c5b21e';
    cp.viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
        url:url,
        layer: "tdtAnnoLayer",
        style: "default",
        maximumLevel:18,//天地图的最大缩放级别
        format: "image/jpeg",
        tileMatrixSetID: "GoogleMapsCompatible",
        show: false
    }));
    //添加地形
    var urlon = "https://www.supermapol.com/realspace/services/3D-stk_terrain/rest/realspace/datas/info/data/path";
    cp.viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
        url: urlon,
        requestVertexNormals: true,
        requestWaterMask: true //水波纹
    });
    window.viewer = cp.viewer;
        // viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
        //     url: "http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}"
        // }));
    const leftClickHandler = new Cesium.ScreenSpaceEventHandler(viewer.canvas)
    const mousemoveHandler = new Cesium.ScreenSpaceEventHandler(viewer.canvas)
    leftClickHandler.setInputAction(function (movement) {
        const pickedObject = viewer.scene.pick(movement.position)
        // ie中通过GraphicLayer加载的对象可以通过该方法拾取
        // const pickedObject = that.viewer.graphicLayer.pickByCoordinate(movement.position.x, movement.position.y)
        if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id) && typeof pickedObject.id.leftClick === 'function') {
            pickedObject.id.leftClick(pickedObject.id)
        } else {
            const oneDiv = window.document.getElementById("gzinfoBox")
            oneDiv.style.display = 'none'
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    // var simpleThrottleFunc = simpleThrottle(mouseMoveEvent, 100, this)
    let timer = null;
    mousemoveHandler.setInputAction(function mouseMove(movement) {
        //const pickedObject = viewer.scene.pick(movement.position)
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            const pickedObject = viewer.scene.pick(movement.endPosition)
            if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id) && typeof pickedObject.id.moveMove === 'function') {
                if (cp.currentEntity) {
                    cp.currentEntity.label.show = false;
                    cp.currentEntity = null
                }
                pickedObject.id.moveMove(pickedObject.id)
            } else {
                // const oneDiv = window.document.getElementById("gzinfoBox")
                // oneDiv.style.display = 'none'
                if (cp.currentEntity) {
                    cp.currentEntity.label.show = false;
                    cp.currentEntity = null
                }
            }
        }, 70)

    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    //结束
}
cp.addBillboard = function (id, position, img, text, type, event) {
    let simplePointEntity = cp.viewer.entities.add({
        id: id, //
        position: Cesium.Cartesian3.fromDegrees(position[0], position[1], 100),
        billboard: {
            image: img,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            //color : Cesium.Color.LIME, // default: WHITE
            width: 20,
            height: 20,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            //scaleByDistance: new Cesium.NearFarScalar(30000, 1, 4000000, 0.2),
        },
        label: {
            text: text,
            show: false,
            font: '14pt Source Han Sans CN', //字体样式
            fillColor: Cesium.Color.BLACK, //字体颜色
            backgroundColor: Cesium.Color.WHITE, //背景颜色
            showBackground: true, //是否显示背景颜色
            outlineColor: Cesium.Color.DARKGOLDENROD,
            style: Cesium.LabelStyle.BLACK, //label样式
            outlineWidth: 1,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            verticalOrigin: Cesium.VerticalOrigin.TOP, //垂直位置
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平位置
            pixelOffset: new Cesium.Cartesian2(0, -55) //偏移
        },
        cursor: true
    })
    simplePointEntity.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
    if (type && event) {
        simplePointEntity[type] = event
    }
},
    cp.addBillboard1 = function (id, position, img, text, type, event) {
        let simplePointEntity = cp.viewer.entities.add({
            id: id, //
            position: Cesium.Cartesian3.fromDegrees(position[0], position[1], 100),
            billboard: {
                image: img,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                //color : Cesium.Color.LIME, // default: WHITE
                width: 40,
                height: 60,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                //scaleByDistance: new Cesium.NearFarScalar(30000, 1, 4000000, 0.2),
            },
            label: {
                text: text,
                show: false,
                font: '14pt Source Han Sans CN', //字体样式
                fillColor: Cesium.Color.WHITE, //字体颜色
                backgroundColor: Cesium.Color.DIMGREY, //背景颜色
                showBackground: false, //是否显示背景颜色
                style: Cesium.LabelStyle.FILL, //label样式
                outlineWidth: 2,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                verticalOrigin: Cesium.VerticalOrigin.TOP, //垂直位置
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平位置
                pixelOffset: new Cesium.Cartesian2(0, -75) //偏移
            },
            cursor: true
        })
        simplePointEntity.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
        if (type && event) {
            simplePointEntity[type] = event
        }
    },
    //添加矢量面和矢量线
    cp.addPloygon = function (id, arr) {
        cp.viewer.entities.add({
            id: id,
            polygon: {
                hierarchy: Cesium.Cartesian3.fromDegreesArray(arr),
                material: Cesium.Color.YELLOW.withAlpha(.3),
                //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            },
            polyline: {
                positions: Cesium.Cartesian3.fromDegreesArray(arr),
                clampToGround: true,
                width: 2,
                material: new Cesium.PolylineOutlineMaterialProperty({
                    color: Cesium.Color.ORANGE,
                    outlineWidth: 1,
                    outlineColor: Cesium.Color.BLACK,
                }),
            },
        });
    }
//添加矢量面和矢量线
cp.addPloygonLine = function (id, arr, color) {
    cp.viewer.entities.add({
        id: id,
        polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(arr),
            clampToGround: true,
            width: 5,
            material: new Cesium.PolylineOutlineMaterialProperty({
                color: color,
                outlineWidth: 1,
                outlineColor: Cesium.Color.BLACK,
            }),
        },
    });
}
cp.flyTo = function (x, y, h, heading, pitch, roll) {
    cp.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(x, y, h), // 设置位置
        orientation: {
            heading: heading, // 方向
            pitch: pitch, // 倾斜角度
            roll: roll
        },
    });
}
cp.getCenter = function () {
    let centerx = (viewer.camera.positionCartographic.longitude * 180) / Math.PI
    let centery = (viewer.camera.positionCartographic.latitude * 180) / Math.PI
    let height = Math.ceil(viewer.camera.positionCartographic.height)
    let heading = viewer.camera.heading
    let pitch = viewer.camera.pitch
    let roll = viewer.camera.roll
    console.log(centerx + ',' + centery + ',' + height + ',' + heading + ',' + pitch + ',' + roll)
},



    cp.addGeoJsonpolygon = function (url) {
        //Cesium.Math.setRandomNumberSeed(0);
        cp.viewer.scene.globe.depthTestAgainstTerrain = true;
        Cesium.GeoJsonDataSource.load(url, {
            //clampToGround: false, //开启贴地
            stroke: Cesium.Color.fromCssColorString('rgba(115,227,230,1)'),
            strokeWidth: 3,
            fill: Cesium.Color.RED.withAlpha(.3)

        }).then(dataSource => {
            cp.viewer.dataSources.add(dataSource)
            var geocacheEntities = dataSource.entities.values
            console.log(geocacheEntities.length)
            for (var i = 0; i < geocacheEntities.length; i++) {

                var entity = geocacheEntities[i]

                //entity.polygon.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
                //entity.polygon.extrudedHeightReference= Cesium.HeightReference.CLAMP_TO_GROUND
                //entity.polygon.height = 1000
                entity.polygon.classificationType = Cesium.ClassificationType.TERRAIN
                //console.log(entity.polygon._heightReference)

            }
            cp.geojsonData[url] = dataSource
            cp.viewer.zoomTo(dataSource);
        })

    },

    cp.removeDataSource = function (url) {
        if (url) {
            cp.viewer.dataSources.remove(cp.geojsonData[url])
            cp.geojsonData[url] = null
        }
    },

    // 放大功能 
    cp.zoomIn = function () {
        let zoomIn = true;
        setTimeout(function () { zoomIn = false; }, 500);
        cp.viewer.clock.onTick.addEventListener(clock => {
            var camera = cp.viewer.camera;
            var ellipsoid = cp.viewer.scene.globe.ellipsoid;
            var cameraHeight = ellipsoid.cartesianToCartographic(
                camera.position
            ).height;
            var moveRate = cameraHeight / 30.0;
            if (zoomIn) {
                camera.moveForward(moveRate);
            }
        });
    }
// 缩小功能
cp.zoomOut = function () {
    let zoomOut = true;
    setTimeout(function () { zoomOut = false; }, 500);
    cp.viewer.clock.onTick.addEventListener(clock => {
        var camera = cp.viewer.camera;
        var ellipsoid = cp.viewer.scene.globe.ellipsoid;
        var cameraHeight = ellipsoid.cartesianToCartographic(
            camera.position
        ).height;
        var moveRate = cameraHeight / 30.0;
        if (zoomOut) {
            camera.moveBackward(moveRate);
        }
    });
}
// 复位功能
cp.reset = function () {
    cp.viewer.camera.flyHome()
}
//************************************************** */
//显示或隐藏地形 
cp.showGaocheng = function (isShow) {
    if (isShow) {
        var urlon = "https://www.supermapol.com/realspace/services/3D-stk_terrain/rest/realspace/datas/info/data/path";
        cp.viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
            url: urlon,
            requestVertexNormals: true,
            requestWaterMask: true //水波纹
        });
    } else {
        cp.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider({
            ellipsoid: Cesium.Ellipsoid.WGS84,
        });
    }
}
//距离计算
cp.juliceliang = function () {
    var viewer = cp.viewer;
    // 取消双击事件-追踪该位置
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
    );

    var handler = new Cesium.ScreenSpaceEventHandler(
        viewer.scene._imageryLayerCollection
    );
    var positions = [];
    var poly = null;
    // var tooltip = document.getElementById("toolTip");
    var distance = 0;
    var cartesian = null;
    var floatingPoint;
    var floatingPointArr = [];
    // tooltip.style.display = "block";

    handler.setInputAction(function (movement) {
        // tooltip.style.left = movement.endPosition.x + 3 + "px";
        // tooltip.style.top = movement.endPosition.y - 25 + "px";
        // tooltip.innerHTML = '<p>单击开始，右击结束</p>';
        // cartesian = viewer.scene.pickPosition(movement.endPosition);
        let ray = viewer.camera.getPickRay(movement.endPosition);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        //cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
        if (positions.length >= 2) {
            if (!Cesium.defined(poly)) {
                poly = new PolyLinePrimitive(positions);
            } else {
                positions.pop();
                // cartesian.y += (1 + Math.random());
                positions.push(cartesian);
            }
            distance = getSpaceDistance(positions);
            // console.log("distance: " + distance);
            // tooltip.innerHTML='<p>'+distance+'米</p>';
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    handler.setInputAction(function (movement) {
        // tooltip.style.display = "none";
        // cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
        // cartesian = viewer.scene.pickPosition(movement.position);
        let ray = viewer.camera.getPickRay(movement.position);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        if (positions.length == 0) {
            positions.push(cartesian.clone());
        }
        positions.push(cartesian);
        //在三维场景中添加Label
        //   var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var textDisance = distance + "米";
        // console.log(textDisance + ",lng:" + cartographic.longitude/Math.PI*180.0);
        floatingPoint = viewer.entities.add({
            name: "空间直线距离",
            // position: Cesium.Cartesian3.fromDegrees(cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180,cartographic.height),
            position: positions[positions.length - 1],
            point: {
                pixelSize: 5,
                color: Cesium.Color.RED,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 2
            },
            label: {
                text: textDisance,
                font: "18px sans-serif",
                fillColor: Cesium.Color.GOLD,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                outlineWidth: 2,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(20, -20)
            }
        });
        floatingPointArr.push(floatingPoint);
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    handler.setInputAction(function (movement) {
        handler.destroy(); //关闭事件句柄
        // viewer.entities.remove(floatingPoint);
        //添加删除按钮
        var deleteBtn = viewer.entities.add({
            id: "deleteBtn",
            position: positions[positions.length - 1],
            //广告牌
            billboard: {
                image:
                    "",
                width: 20,
                height: 20,
                verticalOrigin: Cesium.VerticalOrigin.BASELINE,
                pixelOffset: Cesium.Cartesian2(-60, 60)
            }
        });
        var handler1 = new Cesium.ScreenSpaceEventHandler(
            viewer.scene._imageryLayerCollection
        );
        handler1.setInputAction(function (click) {
            var pick = viewer.scene.pick(click.position);
            //选中某模型   pick选中的对象
            if (Cesium.defined(pick) && pick.id.id === "deleteBtn") {
                for (var i = 0; i < floatingPointArr.length; i++) {
                    viewer.entities.remove(floatingPointArr[i]);
                }
                viewer.entities.remove(deleteBtn);
                handler1.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
                handler1.destroy();
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        positions.pop(); //最后一个点无效
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

    var PolyLinePrimitive = (function () {
        function _(positions) {
            this.options = {
                name: "直线",
                polyline: {
                    show: true,
                    positions: [],
                    material: Cesium.Color.CHARTREUSE,
                    width: 10,
                    clampToGround: true
                }
            };
            this.positions = positions;
            this._init();
        }

        _.prototype._init = function () {
            var _self = this;
            var _update = function () {
                return _self.positions;
            };
            //实时更新polyline.positions
            this.options.polyline.positions = new Cesium.CallbackProperty(
                _update,
                false
            );
            var lineEneity = viewer.entities.add(this.options);
            floatingPointArr.push(lineEneity);
        };

        return _;
    })();
    //空间两点距离计算函数
    function getSpaceDistance(positions) {
        var distance = 0;
        for (var i = 0; i < positions.length - 1; i++) {
            var point1cartographic = Cesium.Cartographic.fromCartesian(
                positions[i]
            );
            var point2cartographic = Cesium.Cartographic.fromCartesian(
                positions[i + 1]
            );
            /**根据经纬度计算出距离**/
            var geodesic = new Cesium.EllipsoidGeodesic();
            geodesic.setEndPoints(point1cartographic, point2cartographic);
            var s = geodesic.surfaceDistance;
            //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
            //返回两点之间的距离
            s = Math.sqrt(
                Math.pow(s, 2) +
                Math.pow(point2cartographic.height - point1cartographic.height, 2)
            );
            distance = distance + s;
        }
        return distance.toFixed(2);
    }
}
//面积计算
cp.mianjiceliang = function () {
    var viewer = cp.viewer;
    // 取消双击事件-追踪该位置
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
    );
    // 鼠标事件
    var handler = new Cesium.ScreenSpaceEventHandler(
        viewer.scene._imageryLayerCollection
    );
    var positions = [];
    var tempPoints = [];
    var polygon = null;
    // var tooltip = document.getElementById("toolTip");
    var cartesian = null;
    var floatingPoint; //浮动点
    // tooltip.style.display = "block";
    var floatingPointArr = [];
    handler.setInputAction(function (movement) {
        // tooltip.style.left = movement.endPosition.x + 3 + "px";
        // tooltip.style.top = movement.endPosition.y - 25 + "px";
        // tooltip.innerHTML ='<p>单击开始，右击结束</p>';
        // cartesian = viewer.scene.pickPosition(movement.endPosition);
        let ray = viewer.camera.getPickRay(movement.endPosition);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        //cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
        if (positions.length >= 2) {
            if (!Cesium.defined(polygon)) {
                polygon = new PolygonPrimitive(positions);
            } else {
                positions.pop();
                // cartesian.y += (1 + Math.random());
                positions.push(cartesian);
            }
            // tooltip.innerHTML='<p>'+distance+'米</p>';
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    handler.setInputAction(function (movement) {
        // tooltip.style.display = "none";
        // cartesian = viewer.scene.pickPosition(movement.position);
        let ray = viewer.camera.getPickRay(movement.position);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        // cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
        if (positions.length == 0) {
            positions.push(cartesian.clone());
        }
        //positions.pop();
        positions.push(cartesian);
        //在三维场景中添加点
        var cartographic = Cesium.Cartographic.fromCartesian(
            positions[positions.length - 1]
        );
        var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
        var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
        var heightString = cartographic.height;
        tempPoints.push({
            lon: longitudeString,
            lat: latitudeString,
            hei: heightString
        });
        floatingPoint = viewer.entities.add({
            name: "多边形面积",
            position: positions[positions.length - 1],
            point: {
                pixelSize: 5,
                color: Cesium.Color.RED,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 2
            }
        });
        floatingPointArr.push(floatingPoint);
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    handler.setInputAction(function (movement) {
        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        handler.destroy();
        positions.pop();
        viewer.entities.remove(floatingPoint);
        //tempPoints.pop();
        // viewer.entities.remove(floatingPoint);
        // tooltip.style.display = "none";
        //在三维场景中添加点
        // var cartographic = Cesium.Cartographic.fromCartesian(positions[positions.length - 1]);
        // var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
        // var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
        // var heightString = cartographic.height;
        // tempPoints.push({ lon: longitudeString, lat: latitudeString ,hei:heightString});
        var deleteBtn = viewer.entities.add({
            id: "deleteBtn",
            position: positions[positions.length - 1],
            //广告牌
            billboard: {
                image:
                    "",
                width: 20,
                height: 20
            }
        });
        var handler1 = new Cesium.ScreenSpaceEventHandler(
            viewer.scene._imageryLayerCollection
        );
        handler1.setInputAction(function (click) {
            var pick = viewer.scene.pick(click.position);
            //选中某模型   pick选中的对象
            if (Cesium.defined(pick) && pick.id.id === "deleteBtn") {
                for (var i = 0; i < floatingPointArr.length; i++) {
                    viewer.entities.remove(floatingPointArr[i]);
                }
                viewer.entities.remove(deleteBtn);
                handler1.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
                handler1.destroy();
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        var textArea = getArea(tempPoints) + "平方公里";
        var areaEntity = viewer.entities.add({
            name: "多边形面积",
            position: positions[positions.length - 1],
            // point : {
            //  pixelSize : 5,
            //  color : Cesium.Color.RED,
            //  outlineColor : Cesium.Color.WHITE,
            //  outlineWidth : 2,
            //  heightReference:Cesium.HeightReference.CLAMP_TO_GROUND
            // },
            label: {
                text: textArea,
                font: "18px sans-serif",
                fillColor: Cesium.Color.GOLD,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                outlineWidth: 2,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(20, -40),
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            }
        });
        floatingPointArr.push(areaEntity);
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

    var radiansPerDegree = Math.PI / 180.0; //角度转化为弧度(rad)
    var degreesPerRadian = 180.0 / Math.PI; //弧度转化为角度

    //计算多边形面积
    function getArea(points) {
        var res = 0;
        //拆分三角曲面

        for (var i = 0; i < points.length - 2; i++) {
            var j = (i + 1) % points.length;
            var k = (i + 2) % points.length;
            var totalAngle = Angle(points[i], points[j], points[k]);

            var dis_temp1 = distance(positions[i], positions[j]);
            var dis_temp2 = distance(positions[j], positions[k]);
            res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle));
            console.log(res);
        }

        return (res / 1000000.0).toFixed(4);
    }

    /*角度*/
    function Angle(p1, p2, p3) {
        var bearing21 = Bearing(p2, p1);
        var bearing23 = Bearing(p2, p3);
        var angle = bearing21 - bearing23;
        if (angle < 0) {
            angle += 360;
        }
        return angle;
    }
    /*方向*/
    function Bearing(from, to) {
        var lat1 = from.lat * radiansPerDegree;
        var lon1 = from.lon * radiansPerDegree;
        var lat2 = to.lat * radiansPerDegree;
        var lon2 = to.lon * radiansPerDegree;
        var angle = -Math.atan2(
            Math.sin(lon1 - lon2) * Math.cos(lat2),
            Math.cos(lat1) * Math.sin(lat2) -
            Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)
        );
        if (angle < 0) {
            angle += Math.PI * 2.0;
        }
        angle = angle * degreesPerRadian; //角度
        return angle;
    }

    var PolygonPrimitive = (function () {
        function _(positions) {
            this.options = {
                name: "多边形",
                polygon: {
                    hierarchy: [],
                    // perPositionHeight : true,
                    material: Cesium.Color.GREEN.withAlpha(0.5)
                    // heightReference:20000
                }
            };

            this.hierarchy = { positions };
            this._init();
        }

        _.prototype._init = function () {
            var _self = this;
            var _update = function () {
                return _self.hierarchy;
            };
            //实时更新polygon.hierarchy
            this.options.polygon.hierarchy = new Cesium.CallbackProperty(
                _update,
                false
            );
            var polygonEntity = viewer.entities.add(this.options);
            floatingPointArr.push(polygonEntity);
        };

        return _;
    })();

    function distance(point1, point2) {
        var point1cartographic = Cesium.Cartographic.fromCartesian(point1);
        var point2cartographic = Cesium.Cartographic.fromCartesian(point2);
        /**根据经纬度计算出距离**/
        var geodesic = new Cesium.EllipsoidGeodesic();
        geodesic.setEndPoints(point1cartographic, point2cartographic);
        var s = geodesic.surfaceDistance;
        //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
        //返回两点之间的距离
        s = Math.sqrt(
            Math.pow(s, 2) +
            Math.pow(point2cartographic.height - point1cartographic.height, 2)
        );
        return s;
    }
}
//淹没分析
cp.yanmofenxi = function (isShow) {
    if (isShow) {
        let opt = new GV.FloodAnalysisOpt()
        cp.viewer.analysis.floodAnalysis.open(opt);
    } else {
        cp.viewer.analysis.floodAnalysis.close()
    }

}
//开启绕点飞行
cp.raodianStart = function (lng, lat, height) {
    var viewer = cp.viewer;
    var position = Cesium.Cartesian3.fromDegrees(lng, lat-.1, height);
    // 相机看点的角度，如果大于0那么则是从地底往上看，所以要为负值，这里取-30度
    var pitch = Cesium.Math.toRadians(-60);
    // 给定飞行一周所需时间，比如10s, 那么每秒转动度数
    var angle = 360 / 30;
    // 给定相机距离点多少距离飞行，这里取值为5000m
    var distance = 5000;
    var startTime = Cesium.JulianDate.fromDate(new Date());

    // var stopTime = Cesium.JulianDate.addSeconds(startTime, 10, new Cesium.JulianDate());

    viewer.clock.startTime = startTime.clone();  // 开始时间
    // viewer.clock.stopTime = stopTime.clone();     // 结速时间
    viewer.clock.currentTime = startTime.clone(); // 当前时间
    viewer.clock.clockRange = Cesium.ClockRange.CLAMPED; // 行为方式
    viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK; // 时钟设置为当前系统时间; 忽略所有其他设置。
    // 相机的当前heading
    var initialHeading = viewer.camera.heading;
    flyEvent = function TimeExecution() {
        // 当前已经过去的时间，单位s
        var delTime = Cesium.JulianDate.secondsDifference(viewer.clock.currentTime, viewer.clock.startTime);
        var heading = Cesium.Math.toRadians(delTime * angle) + initialHeading;
        viewer.scene.camera.setView({
            destination: position, // 点的坐标
            orientation: {
                heading: heading,
                pitch: pitch,

            }
        });
        viewer.scene.camera.moveBackward(distance);

        if (Cesium.JulianDate.compare(viewer.clock.currentTime, viewer.clock.stopTime) >= 0) {
            viewer.clock.onTick.removeEventListener(Exection);
        }
    };

    viewer.clock.onTick.addEventListener(flyEvent);
}
//停止绕点飞行
cp.raodianStop = function () {
    viewer.clock.onTick.removeEventListener(flyEvent);
}

//统一导出该模块，包含方法和所需变量
export default cp;